package com.codedef.library.service;

import com.codedef.library.entity.Task;
import com.codedef.library.repository.TaskRepository;
import com.codedef.library.util.ArrayUtil;
import com.codedef.library.util.Reserver;
import com.codedef.library.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TaskService {

    @Autowired
    TaskRepository taskRepository;

    @Autowired
    MailService mailService;

    // ************************ CURD START ************************

    /**
     * 查询数据库中所有的任务记录
     * @return List<Task>
     */
    public List<Task> getAllTask() {
        return taskRepository.findAll();
    }

    /**
     * 更新一个Task
     * @param task
     * @return
     */
    public boolean updateOneTask(Task task) {
        return taskRepository.save(task) != null ? true : false;
    }



    // ************************ CURD END ************************

    private void sendMail(String to, String subject, String content) {
        mailService.sendHtmlMail(to, subject, content);
    }

    /**
     * 执行一个预约任务
     * @return
     */
    public boolean execOneTask(Task task) {  //今天要进行预约
        //sendMail("1138794994@qq.com", "图书馆预系统Log", "开始执行任务" + task.getId() + ":<br>:" + task);

        boolean isSuccess = false;

        Map<String, Reserver> reserverMap = new HashMap<>();

        //数据库中的str分离成数组
        String[] usernames = {};
        String[] passwords = {};
        String[] seatNums = {};
        usernames = task.getUsernames() != null ? ArrayUtil.stringSplitToArray(task.getUsernames(), ",") : usernames;
        passwords = task.getPasswords() != null ? ArrayUtil.stringSplitToArray(task.getPasswords(), ",") : passwords;
        seatNums = task.getSeatNums() != null ? ArrayUtil.stringSplitToArray(task.getSeatNums(), ",") : seatNums;

//        String atDate = task.getType() == 1 ? DateUtil.getDateStr(task.getDate()) : DateUtil.tomorrowDateStr();
        String atDate = DateUtil.tomorrowDateStr();

        //获取每个人的Reserver实例 并登陆
        for (int i = 0; i < usernames.length; i++) {
            Reserver reserver = new Reserver();
            reserverMap.put(usernames[i], reserver);
            //login
            if (reserver.login(usernames[i], passwords[i]) == true) {
                log.info(usernames[i] + "登陆成功");
                //sendMail("1138794994@qq.com", "图书馆预系统Log", usernames[i] + "登陆成功");
            }
            else {
                log.info(usernames[i] + "登陆失败");
                //sendMail("1138794994@qq.com", "图书馆预系统Log", usernames[i] + "登陆失败");
            }

        }

        //循环多少轮
        for (int round = 0; round < seatNums.length / usernames.length; round++) {

            //每轮预约多少人
            int people;
            for (people = 0; people < usernames.length; people++) {

                // 执行预约
                if (reserverMap.get(usernames[people]).reserve(atDate,
                        seatNums[round * (usernames.length) + people],
                        atDate + ' ' + task.getStarTime(),
                        atDate + ' ' + task.getEndTime())) {
                    //预约成功
                    log.info(usernames[people] + "预约" + seatNums[round * (usernames.length) + people] + "成功");
                    // sendMail("1138794994@qq.com", "图书馆预系统Log", usernames[people] + "预约" + seatNums[round * (usernames.length) + people] + "成功");
                } else {
                    //预约失败，准备回滚
                    log.info(usernames[people] + "预约" + seatNums[round * (usernames.length) + people] + "失败");
                    //sendMail("1138794994@qq.com", "图书馆预系统Log", usernames[people] + "预约" + seatNums[round * (usernames.length) + people] + "失败");
                    for (int k = 0; k < people; k++) {
                        if (!reserverMap.get(usernames[k]).cancelOrder()) {
                            //取消预约失败  最坏情况
                            log.info(usernames[k] + "取消预约失败");
                            //sendMail("1138794994@qq.com", "图书馆预系统Log", usernames[k] + "取消预约失败");
                            // TODO...
                        } else {
                            log.info(usernames[k] + "取消预约成功");
                            //sendMail("1138794994@qq.com", "图书馆预系统Log", usernames[k] + "取消预约成功");
                        }

                    }
                    // 跳出本轮预约，执行下一轮
                    break;
                }

            }

            // 中间没有跳出，说明全部预约成功
            if (people == usernames.length) {
                isSuccess = true;

                //发送邮件
                String[] emails = ArrayUtil.stringSplitToArray(task.getEmails(), ",");
                for (people = 0; people < usernames.length; people++) {
                    String content = "您已预约%s %s至%s的图书馆座位，请进入图书馆预约系统查看详情。";
                    content = String.format(content, DateUtil.tomorrowDateStr(), task.getStarTime(), task.getEndTime());

                    sendMail(emails[people], "图书馆预约成功提醒", content);

                }
                break;
            }

        } // for


        return isSuccess;
    }

    /**
     * 定时任务
     */
    @Scheduled(cron = "0 3 0 * * ?")  //每天00:05:00执行该任务
    public void timingevice() {
        // 0、准备工作
        //明天日期的字符串
        String tomorrowDateStr = DateUtil.tomorrowDateStr();
        //明天星期的数字
        String tomorrowWeekNum = DateUtil.tomorrowWeekNum() + "";
        //明天日期的数字
        String tomorrowDayNum = tomorrowDateStr.substring(8, 10);

        //因为要进行like查询，所以对Str进行预处理
        tomorrowWeekNum = "%" + tomorrowWeekNum + "%";
        tomorrowDayNum = "%" + tomorrowDayNum + "%";

        // 1、查询出今天的所有任务
        List<Task> tasks = taskRepository.selectTaskComingSoonTask(tomorrowDateStr, tomorrowWeekNum, tomorrowDayNum);

        // 2、调用execOneTask()执行，成功写一条数据库记录，失败写log日志
        for (Task task : tasks) {
            if (execOneTask(task)) {
                log.info("=============任务" + task.getId() + "全部预约成功=============");
                sendMail("1138794994@qq.com", "图书馆Log", "=============任务" + task.getId() + "全部预约成功=============");
            }
            else {
                log.info("=============任务" + task.getId() + "部分预约失败，请手动处理=============");
                sendMail("1138794994@qq.com", "图书馆Log", "=============任务" + task.getId() + "部分预约失败，请手动处理=============");
            }

        }

    }

    public boolean addOne(Task task) {
        return taskRepository.save(task) != null ? true : false;
    }

    public List<Task> queryAll() {
        return taskRepository.findAll();
    }

}
